##
# This class handles the user-creation
class AdminController < ApplicationController
	helper :right
	include RightHelper
  layout  'scaffold'
  ##
  # redirects to list
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }
	# session must be active
	verify :session => 'user',
				 :add_flash => { :error => 
					 							 'you must be logged in to manage user accounts' },
				 :redirect_to => { :controller => 'user', :action => :login}

	before_filter :verify_admin

  ##
  # displays all users
  def list
    @user_pages, @users = paginate :users, :per_page => 10
  end

  ##
  # shows one user
  def show
    @user = User.find(params[:id])
  end

  ##
  # creates a creation form
  def new
    @user = User.new
		@groups = Group.find(:all)
		@selected = Group.find(1)
  end

  ##
  # stores the recently created user in the DB
  def create
    @user = User.new(params[:user])
		
		@user.group = Group.find(params[:groups]) if params[:groups]
		if(@user.group.nil?)
			@user.group = Group.find(1)
		end
    if @user.save
      flash[:notice] = 'User was successfully created.'
      redirect_to :action => 'list'
    else
			@groups = Group.find(:all)
			@selected = @user.group
      render :action => 'new'
    end
  end

  ##
  # creates an edit-form
  def edit
    @user = User.find(params[:id])
		@user.password = ""
		@groups = Group.find(:all)
		@selected = @user.group
  end

  ##
  # updates an user in the DB
  def update
		grp = Group.find(params[:groups])
		if(grp.nil?)
			@groups = Group.find(:all)
			render :action => 'edit'
			return
		end

    @user = User.find(params[:id])
		@user.group = grp
		if(params[:user][:password] != "")
			@user.change_password(params[:user][:password])
		end
		tmp = Hash.new
		params[:user].each do |key, val|
			if(key != "password" && key != "group")
				tmp[key] = val
			end
		end
		# hack!
		tmp[:password_confirmation] = "1234"
		if(@user.update_attributes(tmp))
			flash[:notice] = 'User was successfully updated.'
			redirect_to :action => 'show', :id => @user
		else
			@groups = Group.find(:all)
			@selected = @user.group
			render :action => 'edit'
		end
  end

  ##
  # destroys an user in the DB
  def destroy
    User.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end
